import { generateRoutes, addRoutes} from '@/utils/routerUtils'
import router from '@/router'

// 从 localStorage 获取状态
const getStorageState = () => {
    try {
        const user = JSON.parse(localStorage.getItem('user'))
        const menus = JSON.parse(localStorage.getItem('menus'))
        const token = JSON.parse(localStorage.getItem('token'))
        return {
            user,
            menus,
            token,
            routes: [],
            addRoutes: []
        }
    } catch (e) {
        return {
            user: null,
            menus: [],
            token: null,
            routes: [],
            addRoutes: []
        }
    }
}

const state = getStorageState()

const mutations = {
    SET_USER(state, user) {
        state.user = user
        localStorage.setItem('user', JSON.stringify(user))
    },
    SET_MENUS(state, menus) {
        state.menus = menus
        localStorage.setItem('menus', JSON.stringify(menus))
    },
    SET_TOKEN(state, token) {
        state.token = token
        localStorage.setItem('token', JSON.stringify(token))
    },
    SET_ROUTES(state, routes) {
        state.addRoutes = routes
        state.routes = routes
    },
    LOGOUT(state) {
        // 清除状态
        state.user = null
        state.menus = []
        state.token = null
        state.routes = []
        state.addRoutes = []
        // 清除本地存储
        localStorage.removeItem('user')
        localStorage.removeItem('menus')
        localStorage.removeItem('token')
    }
}

const actions = {
    // 登录
    login({ commit }, { user, menus, token }) {
        commit('SET_USER', user)
        commit('SET_MENUS', menus)
        commit('SET_TOKEN', token)

        // 生成可访问的路由表
        const accessRoutes = generateRoutes(menus)
        commit('SET_ROUTES', accessRoutes)

        // 动态添加可访问路由表
        addRoutes(accessRoutes)

        return accessRoutes
    },

    // 重新加载路由（用于页面刷新时）
    reloadRoutes({ commit, state }) {
        if (state.menus && state.menus.length > 0) {
            const accessRoutes = generateRoutes(state.menus)
            commit('SET_ROUTES', accessRoutes)
            addRoutes(accessRoutes)
            return accessRoutes
        }
        return []
    },

    // 登出
    async logout({ commit }) {
        commit('LOGOUT')
        // 跳转到登录页
        router.push('/login')
    }
}

const getters = {
    getToken: state => state.token
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}

export const getToken = state => state.token
